import { AccountTypeOptions, RegisterTypeOptions, UserTypeOptions } from '@/pages/constant';
import { addCompanyApi } from '@/services/brand';
import useTableList from '@/utils/useTableList';
import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Cascader,
  Col,
  Flex,
  Form,
  Input,
  Modal,
  Radio,
  Row,
  Select,
  Space,
  Table,
  Tag,
} from 'antd';
import React from 'react';
import styles from './index.less';
import {
  ExclamationCircleOutlined,
  PlusOutlined,
  ReloadOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import message from '@/utils/message';
import useEditModal from '@/utils/useEditModal';
import { editUserApi, getUserListApi } from '@/services/system';
import { regChinaMobile, regEmail } from '@/utils/regx';
import useAreas from '@/utils/useAreas';
import useCategory from '@/utils/useCategory';
import { findPathById } from '@/utils';

const Company: React.FC = () => {
  const { loading, form, datasource, page, pageSize, total, onFinish, onPageChange } = useTableList(
    { fetchApi: getUserListApi },
  );
  const { areas } = useAreas();
  const { allCategoryList } = useCategory();

  const {
    loading: editLoading,
    form: editForm,
    currentData,
    setCurrentData,
    onSave,
    onCancel,
  } = useEditModal({
    editApi: editUserApi,
    addApi: addCompanyApi,
    successCb: () => onPageChange(page),
  });
  const changeStatus = (row: any) => {
    Modal.confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '确定更改该条数据的状态吗？',
      okText: '确定',
      cancelText: '取消',
      centered: true,
      onOk: async () => {
        const { rsCode } = await editUserApi({
          id: row.id,
          status: row.status === 0 ? 1 : 0,
        });
        if (rsCode === '00000000') {
          message.success('操作成功');
          onPageChange(page);
        }
      },
    });
  };

  const columns: ColumnsType<any> = [
    {
      title: '用户ID',
      dataIndex: 'id',
      key: 'id',
      width: 200,
    },
    {
      title: '姓名或昵称',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '平台',
      dataIndex: 'os',
      key: 'os',
      width: 100,
    },
    {
      title: '上次登录时间',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime',
      width: 200,
      render: (time: number) => {
        return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '公司名称',
      dataIndex: 'companyName',
      key: 'companyName',
    },
    {
      title: '部门职位',
      dataIndex: 'position',
      key: 'position',
      width: 200,
    },
    {
      title: '注册类型',
      dataIndex: 'registerType',
      key: 'registerType',
      width: 100,
      render: (text) => {
        return text === 1 ? '个人' : '公司';
      },
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 150,
    },
    {
      title: '邮箱',
      dataIndex: 'mail',
      key: 'mail',
      width: 200,
    },
    {
      title: '省份',
      dataIndex: 'provinceName',
      key: 'provinceName',
      width: 150,
    },
    {
      title: '城市',
      dataIndex: 'cityName',
      key: 'cityName',
      width: 150,
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
      width: 250,
    },
    {
      title: '主营产品',
      dataIndex: 'product',
      key: 'product',
      width: 250,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 150,
      render: (status: number) => {
        if (status === 0) {
          return <Tag color="gray">禁用</Tag>;
        } else {
          return <Tag color="green">启用</Tag>;
        }
      },
    },
    {
      title: '地图状态',
      dataIndex: 'joinMapStatus',
      key: 'joinMapStatus',
      width: 150,
      render: (status: number) => {
        if (status === 0) {
          return <Tag color="gray">待审核</Tag>;
        } else if (status === 1) {
          return <Tag color="green">已通过</Tag>;
        } else {
          return <Tag color="red">已拒绝</Tag>;
        }
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 200,
      render: (time: number) => {
        return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 200,
      render: (time: number) => {
        return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: 150,
      align: 'center',
      fixed: 'right',
      render: (_, row) => {
        return (
          <Space>
            {/* <Button
              type="primary"
              size="small"
              onClick={() => {
                const ids: any[] = row.categoryId?.split(',') || [];
                const res: any[] = [];
                ids
                  .map((v) => Number(v))
                  .forEach((id) => {
                    const item = findPathById(allCategoryList, id);
                    if (item) {
                      res.push(item);
                    }
                  });
                setCurrentData({
                  id: row.id,
                  userType: row.userType,
                  accountType: row.accountType,
                  registerType: row.registerType,
                  phone: row.phone,
                  mail: row.mail,
                  username: row.username,
                  companyName: row.companyName,
                  position: row.position,
                  regions: row.province && row.city ? [row.province, row.city] : undefined,
                  address: row.address,
                  product: row.product,
                  isAdmin: row.isAdmin,
                  infoCompleted: row.infoCompleted,
                  status: row.status,
                  categoryId: res,
                });
              }}
            >
              编辑
            </Button> */}
            <Button
              color="primary"
              size="small"
              variant="outlined"
              onClick={() => changeStatus(row)}
            >
              {row.status === 0 ? '启用' : '禁用'}
            </Button>
          </Space>
        );
      },
    },
  ];

  const onOk = () => {
    editForm
      .validateFields()
      .then((row: any) => {
        const query: any = {
          id: row.id,
          userType: row.userType,
          accountType: row.accountType,
          registerType: row.registerType,
          phone: row.phone,
          mail: row.mail,
          username: row.username,
          companyName: row.companyName,
          position: row.position,
          province: row.regions[0] || undefined,
          city: row.regions[1] || undefined,
          address: row.address,
          product: row.product,
          isAdmin: row.isAdmin,
          infoCompleted: row.infoCompleted,
          status: row.status,
          categoryId: row.categoryId?.map((v: any) => v.at(-1)).join(','),
        };
        onSave(query);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  return (
    <PageContainer>
      <Row gutter={[30, 30]} style={{ padding: '15px 30px' }}>
        <div className={styles.search_box}>
          <Form
            form={form}
            onFinish={onFinish}
            onReset={() => onFinish({})}
            labelCol={{
              span: 5,
            }}
            style={{ width: '100%' }}
          >
            <Row gutter={[20, 20]}>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="搜索内容" name="searchText">
                  <Input placeholder="输入用户ID/用户名/手机号/邮箱" />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="注册类型" name="registerType">
                  <Select
                    options={[
                      {
                        value: 1,
                        label: '个人',
                      },
                      {
                        value: 2,
                        label: '企业',
                      },
                    ]}
                    placeholder="请选择"
                    allowClear
                  />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="状态" name="status">
                  <Select
                    options={[
                      {
                        value: 0,
                        label: '禁用',
                      },
                      {
                        value: 1,
                        label: '启用',
                      },
                    ]}
                    placeholder="请选择"
                    allowClear
                  />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="地图状态" name="joinMapStatus">
                  <Select
                    options={[
                      {
                        value: 0,
                        label: '待审核',
                      },
                      {
                        value: 1,
                        label: '已通过',
                      },
                      {
                        value: 2,
                        label: '已拒绝',
                      },
                    ]}
                    placeholder="请选择"
                    allowClear
                  />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={24} lg={24} xl={16} xxl={24}>
                <Flex align="center" justify="flex-end" gap={15}>
                  <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                    查询
                  </Button>
                  <Button htmlType="reset" icon={<ReloadOutlined />}>
                    重置
                  </Button>
                  <Button
                    color="primary"
                    variant="outlined"
                    icon={<PlusOutlined />}
                    onClick={() => setCurrentData({})}
                  >
                    新增
                  </Button>
                </Flex>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={styles.table_box}>
          <Table
            columns={columns}
            dataSource={datasource}
            loading={loading}
            rowKey="id"
            scroll={{ x: 3100 }}
            pagination={{
              current: page,
              pageSize: pageSize,
              total: total,
              showSizeChanger: false,
              showQuickJumper: true,
              onChange: onPageChange,
              showTotal: (total) => `共 ${total} 条数据`,
            }}
          />
        </div>
      </Row>
      <Modal
        title={currentData?.id ? '编辑用户' : '新增用户'}
        centered
        width={800}
        open={!!currentData}
        onCancel={onCancel}
        onOk={onOk}
        okButtonProps={{ loading: editLoading }}
      >
        <Form
          form={editForm}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          style={{ padding: '20px 0' }}
        >
          <Form.Item label="ID" name="id" hidden />
          <Form.Item
            label="用户类型"
            name="userType"
            rules={[{ required: true, message: '请选择用户类型' }]}
          >
            <Select placeholder="请选择用户类型" options={UserTypeOptions} />
          </Form.Item>
          <Form.Item
            label="账号类型"
            name="accountType"
            rules={[{ required: true, message: '请选择账号类型' }]}
          >
            <Select placeholder="请选择账号类型" options={AccountTypeOptions} />
          </Form.Item>
          <Form.Item
            label="注册类型"
            name="registerType"
            rules={[{ required: true, message: '请选择注册类型' }]}
          >
            <Select placeholder="请选择注册类型" options={RegisterTypeOptions} />
          </Form.Item>
          <Form.Item
            label="手机号码"
            name="phone"
            rules={[
              { required: true, message: '请输入手机号码' },
              {
                pattern: regChinaMobile,
                message: '请输入正确的手机号码',
              },
            ]}
          >
            <Input placeholder="请输入手机号码" />
          </Form.Item>
          <Form.Item
            label="邮箱"
            name="mail"
            rules={[
              {
                pattern: regEmail,
                message: '请输入正确的手机号码',
              },
            ]}
          >
            <Input placeholder="请输入姓名/昵称" />
          </Form.Item>
          <Form.Item label="姓名/昵称" name="username">
            <Input placeholder="请输入姓名/昵称" />
          </Form.Item>
          <Form.Item label="公司名称" name="companyName">
            <Input placeholder="请输入公司名称" />
          </Form.Item>
          <Form.Item label="部门职位" name="position">
            <Input placeholder="请输入部门职位" />
          </Form.Item>
          <Form.Item label="省市区" name="regions">
            <Cascader
              placeholder="请选择省市区"
              options={areas}
              fieldNames={{
                value: 'id',
                label: 'name',
                children: 'children',
              }}
            />
          </Form.Item>
          <Form.Item label="地址" name="address">
            <Input placeholder="请输入地址" />
          </Form.Item>
          <Form.Item label="标签" name="categoryId">
            <Cascader
              placeholder="请选择标签（可多选）"
              options={allCategoryList}
              fieldNames={{
                value: 'id',
                label: 'name',
                children: 'children',
              }}
              multiple
            />
          </Form.Item>
          <Form.Item label="主营产品/业务" name="product">
            <Input placeholder="请输入主营产品/业务" />
          </Form.Item>
          <Form.Item label="管理后台人员" name="isAdmin" initialValue={0}>
            <Radio.Group>
              <Radio value={0}>否</Radio>
              <Radio value={1}>是</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="信息是否补充完整" name="infoCompleted" initialValue={0}>
            <Radio.Group>
              <Radio value={0}>否</Radio>
              <Radio value={1}>是</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="状态" name="status" initialValue={1}>
            <Radio.Group>
              <Radio value={0}>禁用</Radio>
              <Radio value={1}>启用</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default Company;
